﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Seven.Tools.Extension;

namespace Seven.Pool.Controllers
{
    public class HomeController : Controller
    {
        public ViewResult Index(string account, string password)
        {
            if (account != Seven.Pool.PoolConfig.Config.PoolAdminAccount && password != Seven.Pool.PoolConfig.Config.PoolAdminPassword)
            { return View("Index2"); }

            ViewBag.SignalRAdminAccount = SignalR.Config.SignalRAdminAccount;
            ViewBag.SignalRAdminGroup = SignalR.Config.SignalRAdminGroup;

            return View();
        }

        public ViewResult Index2()
        {
            return View();
        }

        /// <summary>
        /// 获取服务池数据
        /// </summary>
        /// <returns></returns>
        public JsonResult GetCurrentData()
        {
            var allConnection = SignalR.MemberClient.AllTokens;
            var allUser = Member.MemberClient.OnlineTokens;
            int jg = Seven.Member.Common.Config.SessionTimeout;

            var obj = new List<object>();
            foreach (var s in allUser.TryOrderBy(o => o.LoginTime))
            {
                var connect = allConnection.FirstOrDefault(f => f.UserPoolGuid.Equals(s.Guid));
                if (connect.IsNull())
                {
                    obj.Add(new
                    {
                        ID = s.Guid,
                        Account = s.Account,
                        LoginTime = s.LoginTime.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                        LastRequestTime = s.LastRequestTime.IsNull() ? "还未进行请求" : s.LastRequestTime.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                        SignalRID = DBNull.Value,
                        SignalRConnectTime = DBNull.Value,
                        SignalRGroupName = DBNull.Value,
                        OverTime = s.LastRequestTime.IsNull() ? "还未进行请求" : GetDiffDes(DateTime.Now, s.LastRequestTime.Value.AddMinutes(jg))
                    });
                }
                else
                {
                    obj.Add(new
                    {
                        ID = s.Guid,
                        Account = s.Account,
                        LoginTime = s.LoginTime.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                        LastRequestTime = s.LastRequestTime.IsNull() ? "还未进行请求" : s.LastRequestTime.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                        SignalRID = connect.Guid,
                        SignalRConnectTime = connect.FirstConnectTime.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                        SignalRGroupName = connect.GroupName,
                        OverTime = s.LastRequestTime.IsNull() ? "还未进行请求" : GetDiffDes(DateTime.Now, s.LastRequestTime.Value.AddMinutes(jg))
                    });
                }
            }

            return Json(obj);
        }

        /// <summary>
        /// 清空用户池数据
        /// </summary>
        /// <returns></returns>
        public JsonResult ClearMemberPool()
        {
            Member.MemberClient.ClearMemberPool();
            return Json(new { success = true });
        }

        /// <summary>
        /// 获取服务池中用户数量和signalr连接数量
        /// </summary>
        /// <returns></returns>
        public JsonResult GetPoolCount()
        {
            int userCount = Member.MemberClient.OnlineTokensCount;
            int signalRCount = SignalR.MemberClient.AllTokensCount;
            var countPerDay = MemberServiceController.CountPerDay;
            string day = DateTime.Now.ToString("yyyy-MM-dd");
            int todayCount = countPerDay.ContainsKey(day) ? countPerDay[day] : 0;

            return Json(new { userCount = userCount, signalRCount = signalRCount, todayCount = todayCount });
        }

        /// <summary>
        /// 返回date1距离date2的时间间隔描述
        /// 若date1小于date2，则返回描述格式为：几年/几天/几小时/几分/几秒
        /// 若date1大于等于date2，则返回描述格式为：已超时
        /// </summary>
        /// <param name="date1"></param>
        /// <param name="date2"></param>
        /// <returns></returns>
        private static string GetDiffDes(DateTime date1, DateTime date2)
        {
            if (date1 >= date2) { return "已超时"; }
            string result = "";

            DateTime begindate = date1;
            DateTime enddate = date2;

            TimeSpan ts = enddate.Subtract(begindate);
            int Days = ts.Days;
            int Hours = ts.Hours;
            int Minutes = ts.Minutes;
            int Seconds = ts.Seconds;

            if (Days >= 365)
            {
                int tempYear = Days / 365;
                result += (tempYear + "年");
            }
            else if (Days > 0)
            { result += (Days + "天"); }

            if (Hours > 0)
            {
                result += (Hours + "小时");
            }

            if (Minutes > 0)
            {
                result += (ts.Minutes + "分");
            }

            if (Seconds > 0)
            {
                result += (ts.Seconds + "秒");
            }

            return result;
        }
    }
}
